{% extends 'rebs/layouts/base.html' %}

{% block title %}{% endblock %}

{% block content %}
    {% load static widget_tweaks %}

    <!-- Start Content-->
    <div class="container-fluid">

        <!-- start page title -->
        {% include 'rebs/partials/content_title.html' with  second_bs="본사 회계 관리" title="입출금 내역 등록" %}
        <!-- end page title -->

        <div class="row">
            <form method="post" id="form1" class="col-12 p-0 needs-validation" novalidate>
                {% csrf_token %}
                {{ formset.management_form }}
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body">

                            {% with menu_order='3' %}
                                {% include 'rebs_cash/partials/head_menu_cash.html' %}
                            {% endwith %}

                            <div class="row">
                                <div class="col-sm-12 col-md-6">
                                    <div class="form-group row mb-3">
                                        <label for="{{ form.deal_date.id_for_label }}"
                                               class="col-3 col-form-label text-center bg-info-lighten">{{ form.deal_date.label }}</label>
                                        <div class="col-9 col-md-8 col-lg-5">
                                            {{ form.deal_date|add_class:"form-control"|attr:"placeholder:거래일자"|attr:"data-provide=datepicker data-date-format=yyyy-mm-dd data-date-autoclose=true data-toggle=input-mask data-mask-format=0000-00-00" }}
                                        </div>
                                    </div>
                                </div>
                                <div class="col-sm-12 col-md-6"></div>
                            </div>

                            <div class="row">
                                <div class="form-group row table-responsive pl-2">
                                    <table class="table table-sm table-hover m-0">
                                        <thead>
                                        <tr>
                                            <th class="text-center" colspan="2">구분</th>
                                            <th class="text-center">계정과목 <a href="#" data-toggle="modal" data-target="#account-subject-modal"><i
                                                class="dripicons-gear"></i></a></th>
                                            {% include 'rebs_cash/partials/account_subject.html' %}
                                            <th class="text-center">적요</th>
                                            <th class="text-center">거래처</th>
                                            <th class="text-center">
                                                거래계좌
                                                <a href="#">
                                                    <i class="dripicons-gear"
                                                       data-toggle="popover"
                                                       data-trigger="hover"
                                                       data-placement="right" title=""
                                                       data-content="거래를 입력할 계좌가 등록되어 있지 않다면 새로 등록하세요."
                                                       data-original-title="계좌 등록"></i>
                                                </a>
                                            </th>
                                            <th class="text-center">입금액</th>
                                            <th class="text-center">출금액</th>
                                            <th class="text-center">증빙자료</th>
                                            <th class="text-center">비고</th>
                                            <th></th>
                                        </tr>
                                        </thead>

                                        <tbody class="empty-form" disabled style="display: none;">
                                        <tr>
                                            <td class="text-center">
                                                <select name="form-__prefix__-cash_category1"
                                                        class="form-control"
                                                        id="id_form-__prefix__-cash_category1"
                                                        onchange="category1_change(this)">
                                                    <option value="" selected="">---------</option>
                                                    <option value="1">입금</option>
                                                    <option value="2">출금</option>
                                                    <option value="3">대체</option>
                                                </select>
                                            </td>
                                            <td class="text-center">
                                                <select name="form-__prefix__-cash_category2" class="form-control"
                                                        id="id_form-__prefix__-cash_category2"
                                                        onchange="category2_change(this)" disabled="">
                                                    <option value="" selected="">---------</option>
                                                    <option value="1">자산</option>
                                                    <option value="2">부채</option>
                                                    <option value="3">자본</option>
                                                    <option value="4">수익</option>
                                                    <option value="5">비용</option>
                                                </select>
                                            </td>
                                            <td class="text-center">
                                                <select name="form-__prefix__-account" class="form-control"
                                                        id="id_form-__prefix__-account" disabled="">
                                                    <option value="" selected="">---------</option>
                                                </select>
                                            </td>
                                            <td class="text-center">
                                                <input type="text" name="form-__prefix__-content" maxlength="100"
                                                       class="form-control" id="id_form-__prefix__-content"
                                                       onblur="sync_transfer(this)" disabled="" placeholder="적요">
                                            </td>
                                            <td class="text-center">
                                                <input type="text" name="form-__prefix__-trader" maxlength="30"
                                                       class="form-control" id="id_form-__prefix__-trader" disabled=""
                                                       placeholder="거래처">
                                            </td>
                                            <td class="text-center">
                                                <select name="form-__prefix__-bank_account" class="form-control"
                                                        id="id_form-__prefix__-bank_account" disabled="">
                                                    <option value="" selected="">---------</option>
                                                    {% for ba in bank_account %}
                                                        <option value="{{ ba.id }}">{{ ba }}</option>
                                                    {% endfor %}
                                                </select>
                                            </td>
                                            <td class="text-center">
                                                <input type="number" name="form-__prefix__-income" min="0"
                                                       class="form-control text-right" id="id_form-__prefix__-income"
                                                       disabled="" placeholder="입금액">
                                            </td>
                                            <td class="text-center">
                                                <input type="number" name="form-__prefix__-outlay" min="0"
                                                       class="form-control text-right" id="id_form-__prefix__-outlay"
                                                       disabled="" placeholder="출금액">
                                            </td>
                                            <td class="text-center">
                                                <select name="form-__prefix__-evidence" class="form-control"
                                                        id="id_form-__prefix__-evidence" disabled="">
                                                    <option value="">---------</option>
                                                    <option value="0" selected="">증빙 없음</option>
                                                    <option value="1">세금계산서</option>
                                                    <option value="2">계산서(면세)</option>
                                                    <option value="3">신용카드전표</option>
                                                    <option value="4">현금영수증</option>
                                                    <option value="5">간이영수증</option>
                                                </select>
                                            </td>
                                            <td class="text-center">
                                                <input type="text" name="form-__prefix__-note" maxlength="255"
                                                       class="form-control" id="id_form-__prefix__-note"
                                                       placeholder="비고" disabled="">
                                            </td>
                                            <td class="pt-2"><a href="javascript:void(0)" class="font-18"
                                                                style="color: #999">
                                                <i class="mdi mdi-close-circle" data-formset-remove-form></i></a>
                                            </td>
                                        </tr>
                                        </tbody>

                                        <tbody class="forms">
                                        {% for form in formset %}
                                            {{ form.errors }}
                                            <tr>
                                                <td class="text-center">
                                                    {{ form.cash_category1|add_class:"form-control"|attr:"required" }}{{ form.cash_category1.errors }}</td>
                                                <td class="text-center">
                                                    {{ form.cash_category2|add_class:"form-control" }}{{ form.cash_category2.errors }}</td>
                                                <td class="text-center">
                                                    {{ form.account|add_class:"form-control" }}{{ form.account.errors }}</td>
                                                <td class="text-center">
                                                    {{ form.content|add_class:"form-control"|attr:"placeholder:적요" }}{{ form.content.errors }}</td>
                                                <td class="text-center">
                                                    {{ form.trader|add_class:"form-control"|attr:"placeholder:거래처" }}{{ form.trader.errors }}</td>
                                                <td class="text-center">
                                                    {{ form.bank_account|add_class:"form-control" }}{{ form.bank_account.errors }}</td>
                                                <td class="text-center">
                                                    {{ form.income|add_class:"form-control text-right"|attr:"placeholder:입금액" }}{{ form.income.errors }}</td>
                                                <td class="text-center">
                                                    {{ form.outlay|add_class:"form-control text-right"|attr:"placeholder:출금액" }}{{ form.outlay.errors }}</td>
                                                <td class="text-center">
                                                    {{ form.evidence|add_class:"form-control" }}{{ form.evidence.errors }}</td>
                                                <td class="text-center">
                                                    {{ form.note|add_class:"form-control"|attr:"placeholder:비고" }}{{ form.note.errors }}</td>
                                                <td></td>
                                            </tr>
                                        {% endfor %}
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <fieldset
                                    class="controls form-row form-group mb-2 row pt-2 col-12 bg-light">
                                <div class="col-12">
                                    <div class="form-group col-12 mt-0 row add-form-row">
                                        <a href="javascript:void(0)" data-formset-add-form><i
                                                class="mdi mdi-plus-circle-outline text-info font-18"></i> 입출금 내역 더 추가하기
                                        </a>
                                    </div>
                                </div>
                            </fieldset>
                        </div>
                    </div>
                </div>
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body">
                            <div class="row">
                                <div class="form-group mb-0 justify-content-end row">
                                    <div class="col-12">
                                        {% if request.user.is_superuser or request.user.staffauth.company_cash > '1' %}
                                            <button type="submit" class="btn btn-primary">등록하기</button>
                                        {% else %}
                                            <button type="button" class="btn btn-outline-secondary"
                                                    onclick="alert('입출금 내역 등록 권한이 없습니다. 관리자에게 문의하여 주십시요.')">조회권한 사용자
                                            </button>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>

    </div> <!-- container -->

{% endblock %}


{% block third_party_js %}

    <script>
      const num = document.getElementById('id_form-TOTAL_FORMS').value

      window.onload = function () {
        document.getElementById('id_deal_date').value = '{% now "Y-m-d" %}'

        for (let i = 0; i < num; i++) {
          document.getElementById('id_form-' + i + '-cash_category1').setAttribute('onchange', 'category1_change(this)')
          document.getElementById('id_form-' + i + '-cash_category2').setAttribute('onchange', 'category2_change(this)')
          document.getElementById('id_form-' + i + '-content').setAttribute('onblur', 'sync_transfer(this)')

          document.getElementById('id_form-' + i + '-cash_category2').disabled = true // 계정 대분류
          document.getElementById('id_form-' + i + '-account').disabled = true        // 계정 과목
          document.getElementById('id_form-' + i + '-content').disabled = true
          document.getElementById('id_form-' + i + '-trader').disabled = true
          document.getElementById('id_form-' + i + '-bank_account').disabled = true
          document.getElementById('id_form-' + i + '-income').disabled = true         // 입금액 폼
          document.getElementById('id_form-' + i + '-outlay').disabled = true         // 출금액 폼
          document.getElementById('id_form-' + i + '-evidence').disabled = true       // 증빙자료 폼
          document.getElementById('id_form-' + i + '-note').disabled = true
        }
      }

      function category1_change(object) {
        let i = parseInt(object.name.substr(5, 1))
        const cash_category2 = document.getElementById('id_form-' + i + '-cash_category2')          // 계정 대분류, --- 필수
        const account = document.getElementById('id_form-' + i + '-account')                        // 계정 과목
        const content = document.getElementById('id_form-' + i + '-content')                        // 적요, --- 필수
        const trader = document.getElementById('id_form-' + i + '-trader')                          // 거래처, --- 필수
        const bank_account = document.getElementById('id_form-' + i + '-bank_account')              // 거래계좌, --- 필수
        const income = document.getElementById('id_form-' + i + '-income')                          // 입금액 폼 --- 필
        const outlay = document.getElementById('id_form-' + i + '-outlay')                          // 출금액 폼 --- 필
        const evidence = document.getElementById('id_form-' + i + '-evidence')
        const note = document.getElementById('id_form-' + i + '-note')

        const next_category1 = document.getElementById('id_form-' + (i + 1) + '-cash_category1')    // 계정 대분류, --- 필수
        const next_category2 = document.getElementById('id_form-' + (i + 1) + '-cash_category2')    // 계정 대분류, --- 필수
        const next_account = document.getElementById('id_form-' + (i + 1) + '-account')
        const next_content = document.getElementById('id_form-' + (i + 1) + '-content')
        const next_trader = document.getElementById('id_form-' + (i + 1) + '-trader')
        const next_bank_account = document.getElementById('id_form-' + (i + 1) + '-bank_account')   // 거래계좌, --- 필수
        const next_income = document.getElementById('id_form-' + (i + 1) + '-income')               // 입금액 폼 --- 필
        const next_outlay = document.getElementById('id_form-' + (i + 1) + '-outlay')
        const next_note = document.getElementById('id_form-' + (i + 1) + '-note')
        const next_evidence = document.getElementById('id_form-' + (i + 1) + '-evidence')

        cash_category2.disabled = (object.value === '') ? true : false
        account.disabled = (object.value === '3' | object.value === '') ? true : false
        content.disabled = (object.value === '') ? true : false
        trader.disabled = (object.value === '3' | object.value === '') ? true : false
        bank_account.disabled = (object.value === '') ? true : false
        income.disabled = (object.value === '1') ? false : true
        outlay.disabled = (object.value === '2' | object.value === '3') ? false : true
        evidence.disabled = (object.value === '2') ? false : true
        note.disabled = (object.value === '') ? true : false

        content.required = (object.value !== '') ? true : false
        trader.required = (object.value !== '3' | object.value !== '') ? true : false
        bank_account.required = (object.value !== '') ? true : false
        income.required = (object.value === '1') ? true : false
        outlay.required = (object.value === '2' | object.value === '3') ? true : false

        if (object.value === '1') { // 입금
          inc(cash_category2)
          get_account(account, '4')
        } else if (object.value === '2') { // 출금
          out(cash_category2)
          get_account(account, '5')
        } else if (object.value == '3') { // 대체일 경우
          trans(cash_category2)
          account.options[0].selected = true

          // 다음 줄 폼이 없으면 추가하는 로직 작성
          if (next_category1 === null) {
            alert('입출금 내역을 한 칸 더 추가하고 다시 시도하세요!')
            cash_category2.options[0].selected = true
            cash_category2.disabled = true
            object.options[0].selected = true
            content.disabled = true
            bank_account.disabled = true
            outlay.disabled = true
            note.disabled = true
          } else {
            internal_transfer(i)
          }
        } else { // '' 값이 없을 때
          cash_category2.options[0].selected = true
          account.options[0].selected = true
          content.value = ''
          trader.value = ''
          bank_account.options[0].selected = true
          income.value = null
          outlay.value = null
          evidence.options[1].selected = true
          note.value = ''
          if (next_category1) {
            next_category1.options[0].selected = true
            next_category2.options[0].selected = true
            next_category2.disabled = true
            next_account.options[0].selected = true
            next_account.disabled = true
            next_content.value = ''
            next_content.disabled = true
            next_bank_account.options[0].selected = true
            next_bank_account.disabled = true
            next_trader.value = ''
            next_trader.disabled = true
            next_bank_account.options[0].selected = true
            next_bank_account.disabled = true
            next_income.value = null
            next_income.disabled = true
            next_outlay.value = null
            next_outlay.disabled = true
            next_evidence.options[1].selected = true
            next_evidence.disabled = true
            next_note.value = ''
            next_note.disabled = true
          }
        }
      }

      function internal_transfer(i) { // 대체 시 다음 라인 폼 세팅
        i = parseInt(i)
        const next_category1 = document.getElementById('id_form-' + (i + 1) + '-cash_category1')    // 계정 대분류, --- 필수
        const next_category2 = document.getElementById('id_form-' + (i + 1) + '-cash_category2')    // 계정 대분류, --- 필수
        const next_account = document.getElementById('id_form-' + (i + 1) + '-account')
        const next_content = document.getElementById('id_form-' + (i + 1) + '-content')
        const next_trader = document.getElementById('id_form-' + (i + 1) + '-trader')
        const next_bank_account = document.getElementById('id_form-' + (i + 1) + '-bank_account')   // 거래계좌, --- 필수
        const next_income = document.getElementById('id_form-' + (i + 1) + '-income')               // 입금액 폼 --- 필
        const next_outlay = document.getElementById('id_form-' + (i + 1) + '-outlay')
        const next_note = document.getElementById('id_form-' + (i + 1) + '-note')

        next_category1.options[3].selected = true

        next_category2.length = 2;
        next_category2.options[1].text = '대 체';
        next_category2.options[1].value = '6';
        next_category2.options[1].selected = true
        next_category2.disabled = false
        next_category2.required = true

        next_account.options[0].selected = true
        next_account.disabled = true // 계정 대분류, --- 필수
        next_content.disabled = false
        next_content.required = true
        next_trader.disabled = true
        next_trader.required = false
        next_bank_account.disabled = false
        next_bank_account.required = true
        next_income.disabled = false
        next_income.required = true
        next_outlay.disabled = true
        next_outlay.required = false
        next_note.disabled = false
      }

      function sync_transfer(obj) {
        const i = parseInt(obj.name.substr(5, 1))
        const currunt = document.getElementById('id_form-' + i + '-cash_category1')
        const next = document.getElementById('id_form-' + (i + 1) + '-cash_category1')
        if (currunt.value === '3' && next.value === '3') {
          document.getElementById('id_form-' + (i + 1) + '-content').value = obj.value
        } else {
          return
        }
      }

      function inc(category2) {
        category2.length = 5;
        category2.options[1].text = '자 산';   //2-1번째 셀렉트바 텍스트 정의
        category2.options[1].value = '1';     //2-1번째 셀렉트바 값 정의
        category2.options[2].text = '부 채';   //2-2번째 셀렉트바 텍스트 정의
        category2.options[2].value = '2';     //2-2번째 셀렉트바 값 정의
        category2.options[3].text = '자 본';   //2-3번째 셀렉트바 텍스트 정의
        category2.options[3].value = '3';     //2-3번째 셀렉트바 값 정의
        category2.options[4].text = '수 익';   //2-4번째 셀렉트바 텍스트 정의
        category2.options[4].value = '4';     //2-4번째 셀렉트바 값 정의
        category2.options[4].selected = true
      }

      function out(category2) {
        category2.length = 5;
        category2.options[1].text = '자 산';
        category2.options[1].value = '1';
        category2.options[2].text = '부 채';
        category2.options[2].value = '2';
        category2.options[3].text = '자 본';
        category2.options[3].value = '3';
        category2.options[4].text = '비 용';
        category2.options[4].value = '5';
        category2.options[4].selected = true
      }

      function trans(category2) {
        category2.length = 2;
        category2.options[1].text = '대 체';
        category2.options[1].value = '6';
        category2.options[1].selected = true
      }

      function category2_change(d1) {                                  // 구분 2 셀 값 변경 시 로직
        const i = d1.name.substr(5, 1)
        const account = document.getElementById('id_form-' + i + '-account')  // 계정 과목

        if (d1.value === '') {
          account.disabled = true
          account.options[0].selected = true
        } else {
          account.disabled = false
          get_account(account, d1.value)
        }
      }

      function get_account(acc, d1) {
        switch (d1) {
          case '1':
            acc.length = {{ account_1.count|add:"1" }}
                {% for data in account_1 %}
                  acc.options[{{ forloop.counter }}].value = '{{ data.id }}'
                  acc.options[{{ forloop.counter }}].text = '{{ data }}'
                {% endfor %}
            break
          case '2':
            acc.length = {{ account_2.count|add:"1" }}
                {% for data in account_2 %}
                  acc.options[{{ forloop.counter }}].value = '{{ data.id }}'
                  acc.options[{{ forloop.counter }}].text = '{{ data }}'
                {% endfor %}
            break
          case '3':
            acc.length = {{ account_3.count|add:"1" }}
                {% for data in account_3 %}
                  acc.options[{{ forloop.counter }}].value = '{{ data.id }}'
                  acc.options[{{ forloop.counter }}].text = '{{ data }}'
                {% endfor %}
            break
          case '4':
            acc.length = {{ account_4.count|add:"1" }}
                {% for data in account_4 %}
                  acc.options[{{ forloop.counter }}].value = '{{ data.id }}'
                  acc.options[{{ forloop.counter }}].text = '{{ data }}'
                {% endfor %}
            break
          case '5':
            acc.length = {{ account_5.count|add:"1" }}
                {% for data in account_5 %}
                  acc.options[{{ forloop.counter }}].value = '{{ data.id }}'
                  acc.options[{{ forloop.counter }}].text = '{{ data }}'
                {% endfor %}
            break
        }
        return acc
      }
    </script>

    <!-- formset add form script -->
    <script src="{% static 'common/js/formset_add_form.js' %}"></script>

{% endblock %}
